package com.hlwxy.ssm.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import com.dingtalk.api.DefaultDingTalkClient;
import com.dingtalk.api.DingTalkClient;
import com.dingtalk.api.request.OapiProcessinstanceGetRequest;
import com.dingtalk.api.request.OapiProcessinstanceListidsRequest;
import com.dingtalk.api.response.OapiProcessinstanceGetResponse;
import com.dingtalk.api.response.OapiProcessinstanceListidsResponse;
import com.hlwxy.ssm.dao.ExcelTextMapper;
import com.hlwxy.ssm.service.DingTalkService;
import com.hlwxy.ssm.util.TokenSingleton;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.TimeUnit;


@Service
public class DingTalkServiceImpl implements DingTalkService {



    @Autowired
    private ExcelTextMapper excelTestMapper;

    public List<Map<String, Object>> findAllData(String key, Long cursor,String stime,String etime) {
        List<Map<String, Object>> dataList=new ArrayList<Map<String, Object>>();
        try{
            Map<String, Object> map;
            List<String> list=this.findDingTalk(key,cursor,stime,etime);
            for(String pro:list){
                map=new HashMap<String, Object>();
                map.put("pro",pro);
                this.getDingTalk(map,pro,key);
                dataList.add(map);
            }
        }catch (Exception e){

        }

        return dataList;
    }

    public List<Map<String, Object>> getAllDataBy4() {
        SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyy-MM-dd");
        String [] proIds={"PROC-3JYJVR1V-8AZVUMZPQGK5O37675UJ3-1GC2YAIJ-2","PROC-F2E12DC0-9D9E-4B03-81B6-F49025B59BA0","PROC-A1DBF454-EADA-485D-9938-70F0C976390B","PROC-1ABF577E-5437-4A16-91F6-83F4F0D9B8C4"};
        List<Map<String, Object>> list=new ArrayList<Map<String, Object>>();
        Long cursor1=1L;
        Long cursor2=1L;
        Long cursor3=1L;
        Long cursor4=1L;
        String stime="2019-04-01";//从19年4月1号开始同步
        String etime=simpleDateFormat.format(new Date());


        boolean res=false;
        for(String pro:proIds){
            this.findDingTalk2(list,pro,cursor1,stime,etime);
        }

        //boolean res=this.findDingTalk2(list,"PROC-3JYJVR1V-8AZVUMZPQGK5O37675UJ3-1GC2YAIJ-2",cursor1,stime,etime);
       // this.findDingTalk2(list,"PROC-F2E12DC0-9D9E-4B03-81B6-F49025B59BA0",cursor2,stime,etime);
        //this.findDingTalk2(list,"PROC-A1DBF454-EADA-485D-9938-70F0C976390B",cursor3,stime,etime);
        //this.findDingTalk2(list,"PROC-1ABF577E-5437-4A16-91F6-83F4F0D9B8C4",cursor4,stime,etime);

        int batchCount = 500; //每批插入数目
        int batchLastIndex = batchCount;
        List<List<Map<String,Object>>> shareList = new ArrayList<List<Map<String,Object>>>();
        for (int index = 0; index < list.size(); ) {
            if (batchLastIndex >= list.size()) {
                batchLastIndex = list.size();
                shareList.add(list.subList(index, batchLastIndex));
                break;
            } else {
                shareList.add(list.subList(index, batchLastIndex));
                index = batchLastIndex;// 设置下一批下标
                batchLastIndex = index + (batchCount - 1);
            }
        }

        if (CollectionUtils.isNotEmpty(shareList)) {
            for (List<Map<String,Object>> subList : shareList) {
                //循环插入数据
                this.excelTestMapper.addBatchList(subList);
            }
        }

        return list;
    }

    public void getAllDataBy3() {
        SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyy-MM-dd");
        String [] proIds={"PROC-3JYJVR1V-8AZVUMZPQGK5O37675UJ3-1GC2YAIJ-2","PROC-F2E12DC0-9D9E-4B03-81B6-F49025B59BA0","PROC-A1DBF454-EADA-485D-9938-70F0C976390B","PROC-1ABF577E-5437-4A16-91F6-83F4F0D9B8C4"};
        List<Map<String, Object>> list=new ArrayList<Map<String, Object>>();
        Long cursor=1L;
        String nowTime= simpleDateFormat.format(new Date());
        boolean res=false;
        try{

            for(String pro:proIds){
                this.findDingTalk2(list,pro,cursor,nowTime,nowTime);
            }

            int batchCount = 500; //每批插入数目
            int batchLastIndex = batchCount;
            List<List<Map<String,Object>>> shareList = new ArrayList<List<Map<String,Object>>>();
            for (int index = 0; index < list.size(); ) {
                if (batchLastIndex >= list.size()) {
                    batchLastIndex = list.size();
                    shareList.add(list.subList(index, batchLastIndex));
                    break;
                } else {
                    shareList.add(list.subList(index, batchLastIndex));
                    index = batchLastIndex;// 设置下一批下标
                    batchLastIndex = index + (batchCount - 1);
                }
            }

            if (CollectionUtils.isNotEmpty(shareList)) {
                for (List<Map<String,Object>> subList : shareList) {
                    //循环插入数据
                    this.excelTestMapper.addBatchList(subList);
                }
            }
        }catch (Exception e){
            System.err.println("数据同步失败！！"+simpleDateFormat.format(new Date()));
        }

    }


    /**
     * 获取所有流程
     * @return
     */
    public List<String> findDingTalk(String key,Long cursor,String stime,String etime){
            try{
                DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/processinstance/listids");
                OapiProcessinstanceListidsRequest req = new OapiProcessinstanceListidsRequest();
                req.setProcessCode(key);

                SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                Date date = simpleDateFormat.parse(stime+" 00:00:00");
                Date tate = simpleDateFormat.parse(etime+" 23:59:59");
                req.setStartTime(date.getTime());
                req.setEndTime(tate.getTime());
                req.setSize(10L);
                req.setCursor(cursor);
                OapiProcessinstanceListidsResponse response = client.execute(req, TokenSingleton.getToken());

                return response.getResult().getList();
            }catch (Exception e){
                e.printStackTrace();
            }
            return null;
    }

    /**
     * 获取所有流程
     * @return
     */
    public boolean findDingTalk2(List<Map<String, Object>> dataList,String key,Long cursor,String stime,String etime){
        boolean res=false;
        Map<String, Object> map=null;
        try{
            DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/processinstance/listids");
            OapiProcessinstanceListidsRequest req = new OapiProcessinstanceListidsRequest();
            req.setProcessCode(key);

            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Date date = simpleDateFormat.parse(stime+" 00:00:00");
            Date tate = simpleDateFormat.parse(etime+" 23:59:59");
            req.setStartTime(date.getTime());
            req.setEndTime(tate.getTime());
            req.setSize(20L);
            req.setCursor(cursor);
            OapiProcessinstanceListidsResponse response = client.execute(req, TokenSingleton.getToken());

            List<String> list=response.getResult().getList();

            for(String pro:list){
                map=new HashMap<String, Object>();
                map.put("pro",pro);
                map.put("pro_key",key);
                this.getDingTalk(map,pro,key);
                dataList.add(map);
            }

            if(null==response.getResult().getNextCursor()){
                res =  false;
                cursor=1L;
                return false;
            }else{
                res= true;
                cursor=response.getResult().getNextCursor();
                findDingTalk2(dataList,key,cursor,stime,etime);
            }

        }catch (Exception e){
            System.out.println("######"+map.get("pro"));
            e.printStackTrace();
        }
        return res;
    }


    /**
     * 获取钉钉流程详情接口
     * @param map
     * @param pro
     */
    private void getDingTalk(Map<String,Object> map,String pro,String key){
        try{
            DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/processinstance/get");
            OapiProcessinstanceGetRequest request = new OapiProcessinstanceGetRequest();
            request.setProcessInstanceId(pro);
            OapiProcessinstanceGetResponse response = client.execute(request,TokenSingleton.getToken());
            JSONObject json= JSON.parseObject(response.getBody());
            JSONObject jso=JSON.parseObject(json.getString ("process_instance"));
            //状态
            String status=jso.getString("status");
            map.put("status",status);
            //结果
            String result=jso.getString("result");
            map.put("result",result);
            //创建时间
            String create_time=jso.getString("create_time");
            map.put("create_time",create_time);
            //部门
            String originator_dept_name=jso.getString("originator_dept_name");
            map.put("originator_dept_name",originator_dept_name);
            //userId
            String originator_userid=jso.getString("originator_userid");
            map.put("originator_userid",originator_userid);
            //title
            String title=jso.getString("title");
            map.put("title",title);
            //完成时间
            String finish_time=jso.getString("finish_time");
            map.put("finish_time",finish_time);


            //请假
            if(key.equals("PROC-3JYJVR1V-8AZVUMZPQGK5O37675UJ3-1GC2YAIJ-2")){
                map.put("common",leaveData(map,jso.getString("form_component_values")));
            }

            //出差
            if(key.equals("PROC-F2E12DC0-9D9E-4B03-81B6-F49025B59BA0")){
                map.put("common",travelData(map,jso.getString("form_component_values")));
            }

            //补卡申请
            if(key.equals("PROC-1ABF577E-5437-4A16-91F6-83F4F0D9B8C4")){
                map.put("common",patchCardData(map,jso.getString("form_component_values")));
            }

            //外出
            if(key.equals("PROC-A1DBF454-EADA-485D-9938-70F0C976390B")){
                map.put("common",goOutData(map,jso.getString("form_component_values")));
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }


    /**
     * 外出
     * @param common
     * @return
     */
    public static String goOutData(Map<String,Object> map,String common){
        StringBuffer sb=new StringBuffer();
        try{
            JSONArray jsk=JSON.parseArray(common);
            JSONObject s=JSON.parseObject(jsk.get(0).toString());
            JSONArray j=JSON.parseArray(s.getString("value"));


            JSONObject s2=JSON.parseObject(jsk.get(1).toString());
            map.put("stime",j.getString(0));
            map.put("etime",j.getString(1));
            map.put("stype",j.getString(2)+" "+j.getString(3));

            map.put("qjtype",j.getString(4));
            map.put("qjcommon",s2.getString("value"));
            sb.append("  开始时间:"+j.getString(0));
            sb.append("  结束时间:"+j.getString(1));
            sb.append("  请假时间:"+j.getString(2));
            sb.append("  时间类型:"+j.getString(3));
            sb.append("  "+j.getString(5)+":"+j.getString(4));
            sb.append("  "+s2.getString("name")+":"+s2.getString("value"));
        }catch (Exception e){
            System.out.println("goOutData:"+common);
            System.err.println("pro:"+map.get("pro"));
        }
        return sb.toString();
    }



    /**
     * 出差
     * @param common
     * @return
     */
    public static String travelData(Map<String,Object> map,String common){
        String  res="";
        try{
            JSONArray jsk=JSON.parseArray(common);
            JSONObject s=JSON.parseObject(jsk.get(0).toString());

            StringBuffer sb=new StringBuffer();
            JSONArray jsfk;
            if(null==s.getString("rowValue")){
                jsfk= JSON.parseArray(s.getString("ext_value"));
            }else {
                jsfk= JSON.parseArray(s.getString("rowValue"));
            }
            if(null==jsfk){
                return null;
            }
            JSONObject ssk=JSON.parseObject(jsfk.get(1).toString());

            JSONArray jsonArray= JSON.parseArray(ssk.get("value").toString());

            JSONArray json= JSON.parseArray(JSON.parseObject(jsonArray.get(0).toString()).getString("rowValue"));

            JSONObject ssm=JSON.parseObject(json.get(0).toString());
            // System.out.println("@@@"+ssm);
            String ji=ssm.get("label").toString()+":"+ssm.get("value").toString();
            String ji2=JSON.parseObject(json.get(2).toString()).get("label").toString()+":"+JSON.parseObject(json.get(2).toString()).get("value").toString();
            String ji3=JSON.parseObject(json.get(3).toString()).get("label").toString()+":"+JSON.parseObject(json.get(3).toString()).get("value").toString();
            String stime=JSON.parseObject(json.get(4).toString()).get("label").toString()+":"+JSON.parseObject(json.get(4).toString()).get("value").toString();
            String etime=JSON.parseObject(json.get(5).toString()).get("label").toString()+":"+JSON.parseObject(json.get(5).toString()).get("value").toString();
            JSONObject dura=JSON.parseObject(json.get(6).toString());
            JSONObject dur=JSON.parseObject(dura.getString("extendValue"));
            String durationInDay=dur.getString("durationInDay");
            String durationInHour=dur.getString("durationInHour");
            String sstime=dur.getString("_from");
            String eetime=dur.getString("_to");
            String unit=dur.getString("unit");

            map.put("stime",sstime);
            map.put("etime",eetime);
            map.put("stype",durationInDay+" "+unit);
            //System.out.println(ji+ji2+ji3+sstime+eetime+unit+durationInDay+durationInHour);
              res=ji+"  "+ji2+"   "+ji3+"    "+  stime+"  "+etime+"  出差时间:"+durationInDay +"   单位:"+unit;
        }catch (Exception e){
            e.printStackTrace();
            System.out.println("travelData:"+common);
            System.err.println("pro:"+map.get("pro"));
        }
        return res;
    }

    /**
     * 请假
     * @param common
     * @return
     */
    public static String leaveData(Map<String,Object> map,String common){
        StringBuffer sb=new StringBuffer();
        try{
            JSONArray jsk=JSON.parseArray(common);
            JSONObject s=JSON.parseObject(jsk.get(0).toString());
            JSONArray j=JSON.parseArray(s.getString("value"));


            JSONObject s2=JSON.parseObject(jsk.get(1).toString());
            map.put("stime",j.getString(0));
            map.put("etime",j.getString(1));
            map.put("stype",j.getString(2)+" "+j.getString(3));

            map.put("qjtype",j.getString(4));
            map.put("qjcommon",s2.getString("value"));
            sb.append("  开始时间:"+j.getString(0));
            sb.append("  结束时间:"+j.getString(1));
            sb.append("  请假时间:"+j.getString(2));
            sb.append("  时间类型:"+j.getString(3));
            sb.append("  "+j.getString(5)+":"+j.getString(4));
            sb.append("  "+s2.getString("name")+":"+s2.getString("value"));
        }catch (Exception e){
            System.out.println("leaveData:"+common);
            System.err.println("pro:"+map.get("pro"));
        }
        return sb.toString();
    }

    /**
     * 补卡申请
     * @param common
     * @return
     */
    public static String patchCardData(Map<String,Object> map,String common){
        String sd="";
        try{
            JSONArray jsk=JSON.parseArray(common);
            String time=JSON.parseObject(jsk.getString(2)).getString("value");
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

            sd = sdf.format(new Date(Long.parseLong(time)));
            map.put("stype",sd);
        }catch (Exception e){
            System.out.println("patchCardData:"+common);
            System.err.println("pro:"+map.get("pro"));
        }
        return sd;

    }
}
